package com.xpoint.backend.common;

import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.FileNotFoundException;
import java.sql.SQLIntegrityConstraintViolationException;

@ControllerAdvice(annotations = {RestController.class,Controller.class})
@ResponseBody
public class GlobalExceptionHandler {
    //拦截对应的异常
    @ExceptionHandler(MySQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
//        log.error(ex.getMessage());
//        sql异常
        if(ex.getMessage().contains("Duplicate entry")){ //判断异常中是否包含该字段
            String[] split = ex.getMessage().split(" ");  //根据匹配给定的正则表达式来拆分字符串
//            System.out.println("split"+split.toString());
            String msg = split[2] + "已存在";//将截取的第三个词，拼接成一个字符串
            return R.error(msg);//相应给前端
        }
        return R.error("未知异常");//相应其他的异常
    }

}
